package com.work.cos.service.impl.pay;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.work.cos.domain.vo.ComServiceResVo;
import com.work.cos.domain.vo.pay.OrderPayVo;
import com.work.cos.service.interfc.pay.IOrderService;
import com.work.cos.util.thirdpay.alipay.Alipay;
import com.work.cos.util.thirdpay.alipay.Pay;
import com.work.cos.util.thirdpay.alipay.factory.AlipayAPIClientFactory;
import com.work.cos.util.thirdpay.weixinpay.WeixinPay;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import java.io.UnsupportedEncodingException;
import java.util.Map;

public abstract class OrderServiceImpl implements IOrderService {

    private static final Logger logger	= LoggerFactory.getLogger(OrderServiceImpl.class);


    @Override
    public ComServiceResVo refund(String my_trade_no, String trade_no,int refund_amount) {
        // 发送请求
        String strResponse = null;
        try {
            AlipayClient alipayClient = AlipayAPIClientFactory.getAlipayClient();

            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

            JSONObject json = new JSONObject();
            json.put("out_trade_no",my_trade_no);
            json.put("trade_no ",trade_no);
            json.put("refund_amount",refund_amount/100.0);

            logger.debug("refund JSONObject={}",json.toString());
            request.setBizContent(json.toString());
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            logger.info("refund response={}",response);
            if (response.isSuccess()) {
                return ComServiceResVo.returnSuccessStatus();
            }else {
                logger.info("refund fail SubMsg={},SubCode={}",response.getSubMsg(),response.getSubCode());
                return ComServiceResVo.returnErrorMessage(response.getSubMsg());
            }
        } catch (Exception e) {
            logger.error("alipayRefundRequest={}", e);
            return ComServiceResVo.returnErrorMessage("退款发生异常");
        }
    }

    @Override
    public ComServiceResVo prePay(int payMethod, String orderId,String serviceName) {
        OrderPayVo order = getOrderPayVo(orderId);
        Assert.notNull(order, "不能为空");
        Assert.notNull(order.getBody());
        Assert.notNull(order.getOutTradeNo());
        Assert.notNull(order.getSubject());
        Assert.notNull(order.getTotalFee());

        logger.debug("prePay body="+order.getBody()+"outtradeNo="+order.getOutTradeNo()+"subject="+order.getSubject()+"flee="+order.getTotalFee());
        if (Pay.PayMethod.ALIPAY.getCode() == payMethod)
        {
            String alipayInfo = null; //分 --> 元
            try {
                alipayInfo = Alipay.getAlipayInfo(order.getOutTradeNo(),
                        order.getSubject(), order.getBody(), order.getTotalFee() / 100.00,serviceName);
                logger.debug("prePay alipayInfo={}",alipayInfo);
                return ComServiceResVo.returnEntity(alipayInfo);
            } catch (AlipayApiException e) {
                logger.error("prePay AlipayApiException={}",e);
            } catch (UnsupportedEncodingException e) {
                logger.error("prePay UnsupportedEncodingException={}",e);
            }
            return ComServiceResVo.returnErrorMessage("sorry,初始化数据失败");
        }
        else if (Pay.PayMethod.WEIXIN_PAY.getCode() == payMethod)
        {
            Map<String, String> info = WeixinPay.getWeixinPayInfo(order.getOutTradeNo(),
                    order.getSubject(), order.getBody(), order.getTotalFee());
            
            return ComServiceResVo.returnEntity(info);
        }

        return ComServiceResVo.returnErrorMessage("sorry, 没有你想要的支付方式");
    }

    /**
     * 获取订单支付前处理必须的信息
     *
     * 由业务系统实现
     * @param orderId 本系统订单ID, 数据主键id
     * @return
     */
    protected abstract OrderPayVo getOrderPayVo(String orderId);
}
